package jsyf.oa.service.system;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.oa.dao.system.RightOpDao;
import jsyf.oa.entity.system.RightOPEntity;
import jsyf.oa.facade.system.RightOpFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by Lenovo on 2017/12/11.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class RightOpService implements RightOpFacade {
    @Autowired
    private RightOpDao dao;

    @Override
    public String save(String jsonData) {
        RightOPEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), RightOPEntity.class);
        if (StringUtils.isEmpty(entity.getId()) || "0".equals(entity.getId())) {
            dao.add(entity);
        } else {
            RightOPEntity oldEntity = dao.getById(entity.getId());
            oldEntity.setName(entity.getName());
            oldEntity.setRightId(entity.getRightId());
            oldEntity.setEName(entity.getEName());

            dao.update(oldEntity);
        }
        return entity.getId();
    }

    @Override
    public Boolean removeById(String id) {
        return dao.removeById(id)>0;
    }

    @Override
    public List<JSONObject> getByRightId(String rightId) {
        return dao.getJSONListByCondition(" AND RIGHT_ID = ? ",new Object[]{rightId});
    }

    @Override
    public List<JSONObject> getRightOpByUserId(String userId) {
        StringBuffer sql = new StringBuffer();
        sql.append(" AND ");
        sql.append(" ID IN(SELECT RIGHT_OP_ID FROM T_SYS_USER_2_RIGHT_OP WHERE USER_ID =?) ");
        sql.append(" OR ");
        sql.append(" ID IN(SELECT RIGHT_OP_ID FROM T_SYS_ROLE_NAME_2_RIGHT_OP WHERE ");
        sql.append("   ROLE_NAME_ID IN(SELECT roleNameId FROM V_SYS_USER_2_ROLE WHERE userId= ?) ");
        sql.append("   OR ");
        sql.append("   ROLE_NAME_ID IN(SELECT ROLE_NAME_ID FROM T_SYS_ROLE WHERE ID IN(SELECT ROLE_ID FROM T_SYS_USER WHERE ID = ?)) ");
        sql.append("   )");

        return dao.getJSONListByCondition(sql.toString(),new Object[]{userId,userId,userId});
    }
}
